package com.westcom.healthmate.common.utils;

import com.westcom.healthmate.bean.ResponseBean;
import com.westcom.healthmate.common.constants.ErrorConstants;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Locale;

public class CommonUtils
{
    public static byte[] sliceArray(byte[]source,int offset,int len)
    {
        byte[]res = new byte[len];
        for(int i = 0;i<len;i++)
        {
            res[i] = source[offset+i];
        }
        return res;
    }

    public static Long bytes2Long(byte[] data,int offset,int len)
    {
        Long res = 0l;
        for(int i = offset;i<offset+len;i++)
        {
            long tmp = byte2long(data[i]);
            res = res+(tmp<<(8*(len-((i-offset)+1))));
        }
        return res;
    }

    public static Double bytes2Double(byte[] data,int offset,int len)
    {
        Double res = 0d;
        for(int i = offset;i<offset+len;i++)
        {
            long tmp = byte2long(data[i]);
            res = res+(double)(tmp<<(8*(len-((i-offset)+1))));
        }
        return res;
    }

    public static  String getMACAddress(String ip)
    {
        String str = "";
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    //if (str.indexOf("MAC Address") > 1) {
                    if (str.indexOf("MAC") > 1) {
                        macAddress = str.substring(
                                str.indexOf("=") + 2, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

    public static double byte2double(byte b)
    {
        return b<0?((double)b)+256:(double)b;
    }

    public static long byte2long(byte b)
    {
        return b<0?((long)b)+256:(long)b;
    }

    private final static String mHexStr = "0123456789ABCDEF";
    private final static char[] mChars = mHexStr.toCharArray();
    public static String bytes2HexStr(byte[] b,int len)
    {
        StringBuilder sb = new StringBuilder();
        for (int n=0; n<len; n++)
        {
            sb.append(mChars[(b[n] & 0xFF) >> 4]);
            sb.append(mChars[b[n] & 0x0F]);
        }
        return sb.toString().trim().toUpperCase(Locale.US);
    }

    public static String getEntityAsString(HttpResponse resp)
    {
        try
        {
            return EntityUtils.toString(resp.getEntity(),"UTF-8");
        } catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    public static ResponseBean getResponse(String code, Object data, HttpServletResponse response)
    {
        ResponseBean bean = new ResponseBean();
        bean.setCode(code);
        bean.setData(data);
        ErrorConstants.OperationStatus status = ErrorConstants.OPERATION_STATUS.get(code);
        if(null != status)
        {
            response.setStatus(status.getHttpStatus());
        }
        return bean;
    }

    public static byte[] readFile(String path)
    {
        if(StringUtils.isEmpty(path))
        {
            return null;
        }
        File f = new File(path);
        if(!f.exists())
        {
            return null;
        }

        FileInputStream fis = null;
        try
        {
            byte[] buffer = new byte[1024*1024*5];
            fis = new FileInputStream(f);
            int len = fis.read(buffer);
            byte[] res = new byte[len];
            for(int i= 0;i<len;i++)
            {
                res[i] = buffer[i];
            }
            return res;
        } catch (Exception e)
        {
            e.printStackTrace();
        }finally
        {
            if(null != fis)
            {
                try
                {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void writeFile(String path,byte[] buffer)
    {
        if(StringUtils.isEmpty(path))
        {
            return;
        }
        File f = new File(path);
        FileOutputStream fos = null;
        try
        {
            f.getParentFile().mkdirs();
            fos =new FileOutputStream(f);
            fos.write(buffer);
        }catch(Exception e)
        {
            e.printStackTrace();
        }finally
        {
            if(null != fos)
            {
                try {
                    fos.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String getFileMD5(String path)
    {
        try
        {
            return DigestUtils.md5Hex(new FileInputStream(new File(path)));
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
    public static void disableSSLVerification(DefaultHttpClient httpClient)
    {
        try 
		{
            //Secure Protocol implementation.
            SSLContext ctx = SSLContext.getInstance("SSL");
            //Implementation of a trust manager for X509 certificates
            X509TrustManager tm = new X509TrustManager()
            {

                public void checkClientTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {

                }

                public void checkServerTrusted(X509Certificate[] xcs,
                                               String string) throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            //register https protocol in httpclient's scheme registry
            SchemeRegistry sr = ccm.getSchemeRegistry();
            sr.register(new Scheme("https", 443, ssf));
        } catch (Exception e) 
		{
            e.printStackTrace();
        }
    }
}
